package com.jhx.common.framework;

import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.AnimRes;
import android.support.annotation.DrawableRes;
import android.support.annotation.LayoutRes;
import android.support.annotation.MenuRes;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.jhx.common.R;
import com.jhx.common.utils.DisplayUtil;
import com.jhx.common.widget.CommonToolbar;
import com.jhx.common.widget.LoadingDialog;

import java.util.List;

/**
 * activity基类
 *
 * @author jack 2017-05-17 10:20
 */

public class QuickBaseActivity extends AppCompatActivity {
    private   LinearLayout    mContentView;
    private   String          mCurrentFragmentTag;
    private   FragmentManager mFragmentManager;
    protected LoadingDialog   mLoadingDialog;
    protected TextView        mMenuText;
    protected CommonToolbar   mToolbar;
    protected final String    TAG = getClass().getName();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        mContentView = new LinearLayout(this);
        mContentView.setOrientation(LinearLayout.VERTICAL);
        ViewGroup.MarginLayoutParams layoutParams = new ViewGroup.MarginLayoutParams
                (ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        mContentView.setLayoutParams(layoutParams);
        super.setContentView(mContentView);
    }

    @Override
    public void setContentView(@LayoutRes int layoutResID) {
        View view = LayoutInflater.from(this).inflate(layoutResID, mContentView, false);
        setContentView(view);
    }

    @Override
    public void setContentView(View view) {
        setContentView(view, view.getLayoutParams());
    }

    @Override
    public void setContentView(View view, ViewGroup.LayoutParams params) {
        if(view == null) {
            return;
        }
        if(params == null) {
            params = generateDefaultLayoutParams();
        }
        if(showToolbar()) {
            mToolbar = new CommonToolbar(this);
            ViewGroup.MarginLayoutParams lp = new ViewGroup.MarginLayoutParams
                    (ViewGroup.LayoutParams.MATCH_PARENT, DisplayUtil.dip2px(this, 50));
            mToolbar.setLayoutParams(lp);
            mToolbar.setBackgroundColor(getResources().getColor(R.color.black));
            mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    onNavigationClick(view);
                }
            });
            mToolbar.setPopupTheme(R.style.ToolbarTheme);
            if(mContentView.indexOfChild(mToolbar) == -1) {
                mContentView.addView(mToolbar);
            }
        }
        if(mContentView.indexOfChild(view) == -1) {
        mContentView.addView(view, params);
        }
    }

    /**
     * 是否显示默认的toolabr
     */
    protected boolean showToolbar() {
        return true;
    }

    protected ViewGroup.LayoutParams generateDefaultLayoutParams() {
        return new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
    }

    public void setTitle(String title) {
        if(mToolbar == null || TextUtils.isEmpty(title)) {
            return;
        }
        mToolbar.setTitle(title);
        if(mToolbar.getTitleView() != null) {
            setTitleView(mToolbar.getTitleView());
        }
    }

    public void setNavigationIcon(@DrawableRes int resId) {
        Drawable drawable = getResources().getDrawable(resId);
        setNavigationIcon(drawable);
    }

    public void setNavigationIcon(Drawable drawable) {
        if(mToolbar != null && drawable != null) {
            mToolbar.setNavigationIcon(drawable);
            mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    onNavigationClick(view);
                }
            });
        }
    }

    private void setTitleView(TextView textView) {
        if(textView != null) {
            textView.setTextColor(Color.WHITE);
            textView.setTextSize(20);
        }
    }

    public void onNavigationClick(View view) {
        onBackPressed();
    }

    public int containerId() {
        return 0;
    }

    public void push(Class<? extends Fragment> fragment) {
        push(R.anim.fragment_enter,
             R.anim.fragment_exit,
             R.anim.fragment_pop_enter,
             R.anim.fragment_pop_exit,
             true,
             fragment,
             null);
    }

    public void push(Class<? extends Fragment> fragment, Bundle bundle) {
        push(R.anim.fragment_enter,
             R.anim.fragment_exit,
             R.anim.fragment_pop_enter,
             R.anim.fragment_pop_exit,
             true,
             fragment,
             bundle);
    }

    /**
     * 添加fragment到activity
     * @param fragment
     * @param bundle
     */
    public void push(@AnimRes Integer enterAnim,
                     @AnimRes Integer exitAnim,
                     @AnimRes Integer popEnterAnim,
                     @AnimRes Integer popExitAnim,
                     boolean  addToBackStack,
                     Class<? extends Fragment> fragment,
                     Bundle bundle) {
        if(fragment == null || fragment.getName().equals(mCurrentFragmentTag)) {
            return;
        }
        if(mFragmentManager == null) {
            mFragmentManager = getSupportFragmentManager();
        }
        FragmentTransaction transaction= mFragmentManager.beginTransaction();
        if(enterAnim != null && exitAnim != null && popEnterAnim != null && popExitAnim != null) {
            //必须在add\replace\remove之前调用
            transaction.setCustomAnimations(enterAnim, exitAnim, popEnterAnim, popExitAnim);
        }
        Fragment currentFragment = mFragmentManager.findFragmentByTag(mCurrentFragmentTag);
        if(currentFragment != null) {
            transaction.hide(currentFragment);
            if(transaction.isAddToBackStackAllowed() && addToBackStack) {
                transaction.addToBackStack(mCurrentFragmentTag);
            }
        }
        Fragment targetFragment = mFragmentManager.findFragmentByTag(fragment.getName());
        if(targetFragment != null && !targetFragment.isVisible()) {
            Bundle data = targetFragment.getArguments();
            if(bundle != null && data != null) {
                data.clear();
                data.putAll(bundle);
            }
            transaction.show(targetFragment);
        } else {
            targetFragment = Fragment.instantiate(this, fragment.getName(), bundle);

            if(targetFragment != null) {
                if(containerId() != 0) {
                    transaction.add(containerId(), targetFragment, fragment.getName());
                } else {
                    throw new RuntimeException("请重写containerId()");
                }
            }
        }
        transaction.commitAllowingStateLoss();
        mCurrentFragmentTag = fragment.getName();
    }

    /**
     * 回收fragment
     */
    public void pop() {
        if (mFragmentManager != null) {
            int count = mFragmentManager.getBackStackEntryCount();
            if(count > 0) {
                FragmentManager.BackStackEntry stackEntry = mFragmentManager.getBackStackEntryAt(count - 1);
                mCurrentFragmentTag = stackEntry.getName();
                mFragmentManager.popBackStackImmediate();
                return;
            }
        }
        finish();
    }

    /**
     * 平移切换
     */
    public void switchTo(Class<? extends Fragment> target, Bundle bundle) {
        push(null, null, null, null, false, target, bundle);
    }

    @Override
    public void onBackPressed() {
        List<Fragment> fragmentList = getSupportFragmentManager().getFragments();
        if(fragmentList != null && fragmentList.size() > 0) {
            for(Fragment fragment : fragmentList) {
                if(fragment instanceof QuickBaseFragment) {
                    if(((QuickBaseFragment)fragment).interceptionBack()) {
                        ((QuickBaseFragment)fragment).onBackPressed();
                        return;
                    }
                }
            }
        }
        pop();
    }

    protected void showLoadingDialog() {
        if(mLoadingDialog == null) {
            mLoadingDialog = new LoadingDialog(this);
        }
        mLoadingDialog.dismiss();
        mLoadingDialog.show();
    }

    protected void showLoadingDialog(String message) {
        if (mLoadingDialog == null) {
            mLoadingDialog = new LoadingDialog(this);
        }
        mLoadingDialog.setTitle(message);
        mLoadingDialog.dismiss();
        mLoadingDialog.show();
    }

    protected void hideLoadingDialog() {
        if(mLoadingDialog != null && mLoadingDialog.isShowing()) {
            mLoadingDialog.dismiss();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(mLoadingDialog != null) {
            mLoadingDialog.dismiss();
        }
    }

    @SuppressWarnings("ResourceType")
    protected void setMenuText(String text) {
        mMenuText = new TextView(this);
        ViewGroup.MarginLayoutParams textParams = new ViewGroup.MarginLayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT);
        mMenuText.setLayoutParams(textParams);
        mMenuText.setTextColor(Color.WHITE);
        mMenuText.setPadding(15, 15, 15, 15);
        mMenuText.setText(text);
        if(mToolbar != null) {
            mToolbar.setMenuView(mMenuText);
            mMenuText.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    onMenuTextClick(v);
                }
            });
        }
    }

    protected void setMenu(@MenuRes int menu) {
        if(mToolbar != null) {
            mToolbar.inflateMenu(menu);
            mToolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
                @Override
                public boolean onMenuItemClick(MenuItem item) {
                    onMenuClick(item);
                    return true;
                }
            });
        }
    }

    protected void onMenuClick(MenuItem item) {

    }

    protected void onMenuTextClick(View view) {

    }
}
